package com.webull.information.center.dao;

import com.webull.framework.mvc.ApiException;
import com.webull.framework.util.UtilJdbc;
import com.webull.information.center.common.util.MessageSender;
import com.webull.information.client.model.NewsAssociate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 新闻Dao
 *
 * @author shimingjun
 * @version 1.0
 * @date 2016年6月2日 下午5:08:52
 * @since JDK 1.8
 */
@Repository
public class NewsAssociateDao {
    private static final RowMapper<NewsAssociate> newsRM = BeanPropertyRowMapper.newInstance(NewsAssociate.class);
    protected final Logger logger = LogManager.getLogger(getClass());

    private @Autowired
    JdbcTemplate jdbcTemplate;
    private @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private @Autowired
    DbShardHelper dbShardHelper;

    /**
     * 新增关联新闻的关系
     *
     * @param news
     * @return
     * @since 0.1.0
     */
    public Integer addNewsAssociate(NewsAssociate news) {
        SqlParameterSource parameterSource = JdbcHelper.getSqlParameterSource(news);
        if (!existNewsAssociate(news)) {
            namedParameterJdbcTemplate.update(Sql.ADD_NewsAssociate, parameterSource);
            return 1;
        }
        return 0;
    }

    public boolean existNewsAssociate(NewsAssociate news) {
        SqlParameterSource parameterSource = JdbcHelper.getSqlParameterSource(news);
        return namedParameterJdbcTemplate
                .queryForObject(Sql.exist_NewsAssociate, parameterSource, Integer.class) > 0;
    }

    public List<Integer> searchAssocNewsIds(Integer newsId) throws ApiException {
        return jdbcTemplate.queryForList(Sql.query_NewsAssociate, Integer.class, newsId);
    }

    private class Sql {
        private static final String ADD_NewsAssociate = "insert into wli_news_associate(news_id,ass_news_id) values (:newsId,:assNewsId)";
        private static final String exist_NewsAssociate = "select count(1) from wli_news_associate where news_id = :newsId and ass_news_id = :assNewsId";

        private static final String query_NewsAssociate = "select ass_news_id from wli_news_associate where news_id = ? and del = 0";

    }

}
